package com.mingdinggroup.app.util;

import android.annotation.SuppressLint;
import android.app.Application;
import android.view.View;

import com.mingdinggroup.app.model.User;


/**
 * 账户辅助类，
 * 用于更新用户信息和保存当前账户等操作
 */
public final class AccountHelper {
    private User user;
    private Application application;
    @SuppressLint("StaticFieldLeak")
    private static AccountHelper instances;

    private AccountHelper(Application application) {
        this.application = application;
    }

    public static void init(Application application) {
        instances = new AccountHelper(application);
    }

    public void setUser(User user) {
        this.user = user;
    }

    public static long getUserId() {
        return getUser().getUid();
    }

    public synchronized static User getUser() {
        if (instances == null) {
            //			Log.error("AccountHelper instances is null, you need call init() method.");
            return new User();
        }
        if (instances.user == null)
            instances.user =
                    SharedPreferencesHelper.loadFormSource(instances.application, User.class);
        if (instances.user == null)
            instances.user = new User();
        return instances.user;
    }

    public static void updateUserCache(User user) {
        if (user == null)
            return;
        instances.user = user;
        SharedPreferencesHelper.save(instances.application, user);
    }

    private static void clearUserCache() {
        instances.user = null;
        SharedPreferencesHelper.remove(instances.application, User.class);
    }

    public static void login(User user) {


        // 保存缓存
        updateUserCache(user);
        // 登陆成功,重新启动消息服务;
    }


    /**
     * 退出登陆操作需要传递一个View协助完成延迟检测操作
     */
    public static void logout() {
        // 清除用户缓存
        clearUserCache();

    }

    /**
     * 退出登陆操作需要传递一个View协助完成延迟检测操作
     *
     * @param view     View
     * @param runnable 当清理完成后回调方法
     */
    public static void logout(final View view, final Runnable runnable) {
        // 清除用户缓存
        clearUserCache();
        // 等待缓存清理完成
        view.postDelayed(new Runnable() {
            @Override
            public void run() {
                view.removeCallbacks(this);
                User user = SharedPreferencesHelper.load(instances.application, User.class);
                // 判断当前用户信息是否清理成功
                if (user == null || user.getUid() <= 0) {
                    runnable.run();
                } else {
                    view.postDelayed(this, 200);
                }
            }
        }, 200);

    }

}
